/**
 * Copyright © 2018
 * 
 */
package com.adds.lvds.service.impl.scheduler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adds.lvds.core.plugin.PageView;
import com.adds.lvds.core.utils.CommUtils;
import com.adds.lvds.dao.impl.monit.MonitTaskMapper;
import com.adds.lvds.dao.impl.scheduler.SchedulerMapper;
import com.adds.lvds.model.monit.Monit_task_base;
import com.adds.lvds.model.scheduler.JobDetailModel;

/**
 * @author: zhangjian
 * @date: 2018年6月25日 下午5:15:06
 * @desc 定时任务调度业务处理层
 */
@Service("schedulerService")
@SuppressWarnings("all")
public class SchedulerService {
	@Autowired
	private SchedulerMapper schedulerMapper;
	@Autowired
	private Scheduler scheduler;
	@Autowired
	private MonitTaskMapper monitTaskMapper;
	private Logger log = LogManager.getLogger("schedulerService");

	/**
	 * 获取任务列表
	 * 
	 * @return
	 */
	public JobDetailModel getQrtzTriggersList(Map<String, Object> map) {
		JobDetailModel jobDetailModel = null;
		try {
			jobDetailModel = (JobDetailModel) schedulerMapper.getQrtzTriggersList(map).get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jobDetailModel;
	}

	/**
	 * 分页显示监控任务数据
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public PageView<JobDetailModel> pageQrtzTriggersByCondition(PageView<JobDetailModel> pageView, Monit_task_base t) {
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("paging", pageView);
			map.put("t", t);
			List<JobDetailModel> list = schedulerMapper.pageQrtzTriggersByCondition(map);
			pageView.setRecords(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pageView;
	}

	/**
	 * 发布任务
	 * 
	 * @param jobDetailModel
	 *            任务详情实体
	 * @return 发布成功返回"0",失败返回"1"
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String addJob(JobDetailModel jobDetailModel) {
		String result = CommUtils.SUCC;
		try {
			TriggerKey triggerKey = TriggerKey.triggerKey(jobDetailModel.getJobName(), Scheduler.DEFAULT_GROUP);
			Class cls = Class.forName(jobDetailModel.getJobClassName());
			String jobName = jobDetailModel.getJobName();
			String jobGroup =Scheduler.DEFAULT_GROUP;
			String cron = jobDetailModel.getCronExpression();
			JobDetail job = JobBuilder.newJob(cls).withIdentity(jobName, jobGroup).build();
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
					.withSchedule(CronScheduleBuilder.cronSchedule(cron)).forJob(jobName, jobGroup).build();
			scheduler.scheduleJob(job, trigger);
			if (jobDetailModel.getMonit_switch() == 1 && !scheduler.isShutdown()) {
				scheduler.isStarted();
				log.info(jobName + "  创建任务状态-----start-----");
			} else {
				scheduler.pauseTrigger(triggerKey);
				log.info(jobName + "  创建任务状态-----stop-----");
			}
			Monit_task_base monit_task_base = new Monit_task_base();
			monit_task_base.setMonit_switch(jobDetailModel.getMonit_switch());
			monit_task_base.setPk_dict_id(jobDetailModel.getPk_dict_id());
			monit_task_base.setPk_scene_id(jobDetailModel.getPk_scene_id());
			monit_task_base.setPk_task_id(UUID.randomUUID().toString().replaceAll("-", ""));
			monit_task_base.setTask_name(jobDetailModel.getJobName());
			monit_task_base.setInitial_system(jobDetailModel.getInitial_system());
			monit_task_base.setTarget_system(jobDetailModel.getTarget_system());
			monitTaskMapper.insertMonit_task_base(monit_task_base);
		} catch (Exception e) {
			result = CommUtils.ERROR;
			log.error("[添加任务-失败]-addJob ", e);
			throw new RuntimeException();

		}
		return result;
	}

	/**
	 * 编辑任务
	 * 
	 * @param jobDetailModel
	 *            任务详情实体
	 * @return 发布成功返回"0",失败返回"1"
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String editJob(JobDetailModel jobDetailModel) {
		TriggerKey triggerKey = TriggerKey.triggerKey(jobDetailModel.getJobName(), Scheduler.DEFAULT_GROUP);
		String result = CommUtils.SUCC;
		try {
			Class cls = Class.forName(jobDetailModel.getJobClassName());
			String jobName = jobDetailModel.getJobName();
			String jobGroup = Scheduler.DEFAULT_GROUP;
			String cron = jobDetailModel.getCronExpression();
			JobDetail job = JobBuilder.newJob(cls).withIdentity(jobName, jobGroup).build();
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup)
					.withSchedule(CronScheduleBuilder.cronSchedule(cron)).forJob(jobName, jobGroup).build();
			scheduler.rescheduleJob(triggerKey, trigger);
			if (jobDetailModel.getMonit_switch() == 1 && !scheduler.isShutdown()) {
				scheduler.isStarted();
				log.info(jobName + "  编辑任务状态-----start-----");
			} else {
				scheduler.pauseTrigger(triggerKey);
				log.info(jobName + "  编辑任务状态-----stop-----");
			}
			Monit_task_base monit_task_base = new Monit_task_base();
			monit_task_base.setMonit_switch(jobDetailModel.getMonit_switch());
			monit_task_base.setPk_dict_id(jobDetailModel.getPk_dict_id());
			monit_task_base.setPk_scene_id(jobDetailModel.getPk_scene_id());
			monit_task_base.setPk_task_id(jobDetailModel.getPk_task_id());
			monit_task_base.setInitial_system(jobDetailModel.getInitial_system());
			monit_task_base.setTarget_system(jobDetailModel.getTarget_system());
			monitTaskMapper.editMonit_task_base(monit_task_base);
		} catch (Exception e) {
			log.error("[编辑任务-失败]-editJob ", e);
			throw new RuntimeException(e);
		}
		return result;
	}

	/**
	 * @Description:暂停一个任务(使用默认组名)
	 * @param jobName
	 * @param jobGroupName
	 * 
	 */
	public String pauseJob(String jobName) {
		String result = CommUtils.SUCC;
		JobKey jobKey = JobKey.jobKey(jobName, Scheduler.DEFAULT_GROUP);
		try {
			scheduler.pauseJob(jobKey);
		} catch (Exception e) {
			result = CommUtils.ERROR;
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @Description:启动所有定时任务
	 * 
	 *
	 */
	public String startJobs(String jobName) {
		String result = CommUtils.SUCC;
		TriggerKey triggerKey = TriggerKey.triggerKey(jobName, Scheduler.DEFAULT_GROUP);
		try {
			scheduler.resumeTrigger(triggerKey);
		} catch (Exception e) {
			result = CommUtils.ERROR;
			throw new RuntimeException(e);
		}
		return result;
	}

	/**
	 * 关闭全部定时任务
	 */
	public void shutdownJobs() {
		try {
			if (!scheduler.isShutdown()) {
				scheduler.shutdown();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 根据任务名删除一条任务信息
	 * 
	 * @param jobName
	 * @return
	 */
	public String delJob(String jobName, String jobGroup) {
		String state = CommUtils.ERROR;
		try {
			TriggerKey triggerKey = TriggerKey.triggerKey(jobName, Scheduler.DEFAULT_GROUP);
			scheduler.pauseTrigger(triggerKey);// 停止触发器
			scheduler.unscheduleJob(triggerKey);// 移除触发器
			boolean res = scheduler.deleteJob(new JobKey(jobName, jobGroup));
			if (res) {
				state = CommUtils.SUCC;
				return state;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return state;
	}

	/**
	 * 批量删除任务
	 * 
	 * @param jobNameList
	 * @param jobGroupList
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public String delJob(String[] pk_task_id, String[] jobNameList) {
		String result = CommUtils.SUCC;
		try {
			List<JobKey> list = new ArrayList<JobKey>();
			for (int i = 0; i < jobNameList.length; i++) {
				String jobname = jobNameList[i];
				//list.add(new JobKey(jobname, jobgroup));
				TriggerKey triggerKey = TriggerKey.triggerKey(jobname, Scheduler.DEFAULT_GROUP);
				scheduler.pauseTrigger(triggerKey);// 停止触发器
				scheduler.unscheduleJob(triggerKey);// 移除触发器
				scheduler.deleteJob(new JobKey(jobname, jobname));
			}
			monitTaskMapper.deleteMonit_task_base(pk_task_id);
		} catch (Exception e) {
			log.error("[批量删除任务-失败]-delJob ", e);
			throw new RuntimeException(e);
		}
		return result;
	}
}
